﻿
//全局变量
var spPageUrl = "../ashx/spui.ashx";//后台统一页面
var spPageHtmlName = "本html名称";//如index
var pTableName = "";//增删改的，表名
var pTableIdName = "";//增删改的，表主键
var grid1ID = "";//列表的ID
var selTableinfo = "";//查询table信息 主表一定要as T 
var selFieldsinfo = "*";//查询返回的内容
var pPageCode = "";
var pPageInfoName = "-";
//权限获取
var ptoolbar = "";
//设置页面基本信息
function spsetBase(tname, tid, sinfo, sre, mgid, pcode, infoname, HtmlName) {
    HCUser = createObject("sys");
    pTableName = tname;
    pTableIdName = tid;
    selTableinfo = sinfo;
    selFieldsinfo = sre;
    grid1ID = mgid;
    pPageCode = pcode;
    pPageInfoName = infoname;
    ptoolbar = getToolBar();
    spPageHtmlName = HtmlName;
}
function spsetBaseNoBt(tname, tid, sinfo, sre, mgid, pcode, infoname, HtmlName) {
    HCUser = createObject("sys");
    pTableName = tname;
    pTableIdName = tid;
    selTableinfo = sinfo;
    selFieldsinfo = sre;
    grid1ID = mgid;
    pPageCode = pcode;
    pPageInfoName = infoname;
    spPageHtmlName = HtmlName
}
//////////全局用户信息
var HCUser = null;//createObject("sys");
String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
}
function replaceAll2(content, oldReplace, newReplace) {
    var i;
    for (i = 0; i < content.length; i++) {
        if (content.indexOf(oldReplace) > 0) {
            content = content.replace(oldReplace, newReplace);
        }
    }
    return content;
}
//////////////////**********************主表的删查

//获取查询url 表查
//function spselUrl(spadd)
function spselUrl(spadd) {
    if (spadd != null && spadd != "undefined" && spadd.length > 0)
    { return spPageUrl + "?action=sel&tableinfo=" + selTableinfo + "&refields=" + selFieldsinfo + "&wheresp= " + spadd; }
    else
        return spPageUrl + "?action=sel&tableinfo=" + selTableinfo + "&refields=" + selFieldsinfo + "";
}
//获取查询行url 
//function spselrowUrl(id)
function spselrowUrl(id) {
    return spPageUrl + "?action=GetTableObjINFO&talbename=" + pTableName + "&midname=" + pTableIdName + "&midvalue=" + id;
}
//获取DEL url
//function spdelUrl(id)
function spdelUrl(id) {
    return spPageUrl + "?action=del&tablename=" + pTableName + "&tablemidname=" + pTableIdName + "&id=" + id;
}


//查询树结构
//function sposelTreeUrl(t, r, wa)
function sposelTreeUrl(t, r, wa) {
    if (wa != null && wa != "undefined" && wa.length > 0)
    { return spPageUrl + "?action=seltree&tableinfo= " + t + "&refields= " + r + "&wheresp= " + wa; }
    else
        return spPageUrl + "?action=seltree&tableinfo= " + t + "&refields= " + r + "";
}


function sposelUrl(t, r, wa) {
    if (wa != null && wa != "undefined" && wa.length > 0)
    { return spPageUrl + "?action=sel&tableinfo=" + t + "&refields=" + r + "&wheresp= " + wa; }
    else
        return spPageUrl + "?action=sel&tableinfo=" + t + "&refields=" + r + "";
}
function spodelUrl(t, k, id) {
    return spPageUrl + "?action=del&tablename=" + t + "&tablemidname=" + k + "&id=" + id;
}

//获取查询url_sql(包含 状态+行数据)
function sposelUrlBySql(sqlinfo) {
    return spPageUrl + "?action=SqlTableGet&sqlinfo=" + escape(sqlinfo);
}
//获取查询url_sql（只有行数据）
//function sposelUrlBySqlNoState(sqlinfo)
function sposelUrlBySqlNoState(sqlinfo) {
    return spPageUrl + "?action=SqlTableGet&nostate=no&sqlinfo=" + escape(sqlinfo);
}

//获取查询url_sql(包含 状态+行数据)
function sposelUrlByF(s, t, w, g, h, o) {

    var re = spPageUrl + "?action=SqlTableGet&sqlinfo=" + escape("select[" + s + "]table[" + t + "]where[" + w + "]group[" + g + "]having[" + h + "]order[" + o + "]");
    re = re.replaceAll("'", "hcdhc");
    return re;
}
//获取查询url_sql（只有行数据）
function sposelUrlByFNoState(s, t, w, g, h, o) {

    var re = spPageUrl + "?action=SqlTableGet&nostate=no&sqlinfo=" + escape("select[" + s + "]table[" + t + "]where[" + w + "]group[" + g + "]having[" + h + "]order[" + o + "]");
    re = re.replaceAll("'", "hcdhc");
    return re;
}



//同步请求后台，要求后台，返回直接的json串
function spGetJson(url) {
    var re;
    $.ajax({
        type: "post",
        url: url,
        //  data: "test=" + test,
        async: false,
        success: function (data) {
            re = data;
        }
    });
    return re;
}
var toolbartext = "";
function getToolBar() {

    var toolbar = [];
    $.ajax({
        url: "../ashx/sp.ashx?action=getbuttonaccess&pagecode=" + pPageCode + "&userid=" + HCUser.HCUide,
        type: "post",
        dataType: "json",
        timeout: 5000,
        async: false,
        cache: false,
        success: function (data) {
            if (data.toolbar != undefined && data.toolbar != '') {
                $.each(data.toolbar, function (index, row) {
                    var handler = row.handler;
                    row.handler = function () { eval(handler); };
                    toolbar.push(row);
                    toolbartext += row.text + "-";
                });
            }
        }
    });
    return toolbar;
}
function setToolBar(btstring) {
    var data = $.parseJSON(btstring);
    var toolbar = [];
    if (data.toolbar != undefined && data.toolbar != '') {

        $.each(data.toolbar, function (index, row) {
            var handler = row.handler;
            row.handler = function () { eval(handler); };
            toolbar.push(row);
        });
    }
    ptoolbar = toolbar;
}
function createObject(dowhat) {

    var obj = new Object();
    //从cookie取，如果没有--或者禁用了（从后台取中取）
    if (dowhat == "reload" || hcgetCookie("HCUid") == "" || pPageCode == "index") {
        var linfo = spGetJson("../ashx/sp.ashx?action=getLogininfo&timenow=" + new Date().getTime());
        var lobj = $.parseJSON(linfo);

        obj.HCUide = lobj[0].HCUid;
        obj.HCUname = lobj[0].HCUname;
        obj.HCUtitle = lobj[0].HCUtitle;
        obj.HCUorg = lobj[0].HCUorg;
        obj.HCUdep = lobj[0].HCUdep;
        obj.HCUorgtype = lobj[0].HCUorgtype;

        hcsetCookie("HCUid", obj.HCUide, 1);
        hcsetCookie("HCUname", obj.HCUname, 1);
        //setCookie("HCUtitle", obj.HCUtitle, 1);
        hcsetCookie("HCUorg", obj.HCUorg, 1);
        hcsetCookie("HCUdep", obj.HCUdep, 1);
        hcsetCookie("HCUorgtype", obj.HCUorgtype, 1);
    }
    else {
        obj.HCUide = hcgetCookie("HCUid");
        obj.HCUname = hcgetCookie("HCUname");
        // obj.HCUtitle = hcsetCookie("HCUtitle");
        obj.HCUorg = hcgetCookie("HCUorg");
        obj.HCUdep = hcgetCookie("HCUdep");
        obj.HCUorgtype = hcgetCookie("HCUorgtype");
    }

    return obj;
}
//cookie
function hcsetCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";;
}
//获取cookie
function hcgetCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}
//清除cookie  
function hcclearCookie(name) {
    setCookie(name, "", -1);
}



//通用标准的toolUpdate  itemEditContainer---edititemblock--itemEdit
function toolUpdate() {

    var row = $(grid1ID).datagrid("getSelections");
    if (row.length == 0) {
        $.messager.alert("提示信息", "请选择需要修改的数据！"); return;
    }
    var id = row[0][pTableIdName];
    toolUpdateById(id);
}
//根据行号
function toolUpdateForId(index) {
    $(grid1ID).datagrid("selectRow", index);
    var row = $(grid1ID).datagrid("getSelected");
    var id = row[pTableIdName];
    toolUpdateById(id);
}
//根据ID
function toolUpdateById(id) {
    hcmtable_sno();
    var index = layer.open({
        type: 2,
        title: "修改" + pPageInfoName + "信息",
        content: spPageHtmlName + "-ae.html?action=edit&id=" + id
    });
    layer.full(index);
}

//通用标准的toolDelete  inids:可指定ID，或者根据行选择处理
function toolDelete(inids) {
    var del = 1;
    var ID = "";
    if (inids) {
        hcmtable_sno();
        ID = inids;
    }
    else {
        var rowdata = hcmtable.rows('.selected').data();
        del = rowdata.length;
        for (var i = 0; i < del; i++) {
            ID += rowdata[i][pTableIdName] + ",";
        }
        ID = ID.substring(0, ID.length - 1);
    }
    if (ID.length == 0) {
        layer.alert('请选择要删除的内容');
        return;
    }
    layer.confirm("确认要删除吗？记录数：" + del, function (index) {
        $.get(spdelUrl(ID),
         function (data) {
             var data = JSON.parse(data);
             switch (data.message) {
                 case JsonResult.SessionOut:
                     layer.msg('登录超时，请重新登录!', { icon: 2, time: 1000 });
                     break;
                 case JsonResult.Error:
                     layer.msg('系统出错!' + data.data, { icon: 2, time: 1000 });
                     break;
                 case JsonResult.Success:
                     layer.msg('已删除!', { icon: 1, time: 1000 });
                     // hcmtable_sno();
                     findreolad();
                     break;
             }
         });

    });



}

//通用标准的toolAdd  itemEditContainer---edititemblock--itemEdit
function toolAdd() {
    var index = layer.open({
        type: 2,
        title: "新增" + pPageInfoName + "信息",
        content: spPageHtmlName + "-ae.html?action=add",
        //cancel: function (index) {//关闭
        //    layer.close(index);
        //},
        //success: function (layero, index) {
        //    console.log(layero, index);
        //},
        //yes: function (index) {
        //    //do something
        //    layer.close(index); //一般设定yes回调，必须进行手工关闭
        //},
        end: function () {
            //do something
            //var dfd = 1;
            findreolad(hcdivbackinfo);
        }
    });
    layer.full(index);

}
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}

//本页面查找
function hctsel(whereadd, callback) {
    $.get(spselUrl(whereadd),
            function (data) {
                callback(data);
            });
}
//删除指定数据
function hcdodel(tablename, tablekey, tablekeyid, callback) {
    $.get(spodelUrl(tablename, tablekey, tablekeyid),
                  function (data) {
                      var data = JSON.parse(data);
                      switch (data.message) {
                          case JsonResult.SessionOut:
                              $.messager.alert('系统出错', ' 登录超时，请重新登录!');
                              callback("timeout");
                              break;
                          case JsonResult.Error:
                              $.messager.alert('系统出错', data.data);
                              callback("error");
                              break;
                          case JsonResult.Success:
                              $.messager.show({
                                  title: '提示信息',
                                  msg: data.data,
                                  showType: 'show'
                              });
                              callback("ok");
                              break;
                      }
                  });
}
//添加指定数据 fname1%fvalue1$fname2%fvalue2
function hcdoadd(tablename, fnamevalue, callback) {
    $.ajax({
        type: "post",
        url: spPageUrl,
        data: {
            "action": "doadd",
            "tablename": tablename,
            "fnamevalue": fnamevalue
        },
        timeout: 9000,
        async: true,
        cache: false,
        error: function (error) {
            callback("error");
        },
        success: function (data) {
            var result = JSON.parse(data);
            switch (result.message) {
                case JsonResult.Success:
                    $.messager.show({
                        title: '提示信息',
                        msg: result.data,
                        showType: 'show'
                    });
                    callback("ok");
                    break;
                case JsonResult.Error:
                    callback("error");
                    break;
                default:
                    break;
            }

        }
    });
}
//更新指定数据 fname1%fvalue1$fname2%fvalue2
function hcdoedit(tablename, key, id, fnamevalue, callback) {
    $.ajax({
        type: "post",
        url: spPageUrl,
        data: {
            "action": "doedit",
            "tablename": tablename,
            "tablemidname": tablekey,
            "id": id,
            "fnamevalue": fnamevalue
        },
        timeout: 6000,
        async: true,
        cache: false,
        error: function (error) {
            callback("error");
        },
        success: function (data) {
            var result = JSON.parse(data);
            switch (result.message) {
                case JsonResult.Success:
                    $.messager.show({
                        title: '提示信息',
                        msg: result.data,
                        showType: 'show'
                    });
                    callback("ok");
                    break;
                case JsonResult.Error:
                    callback("error");
                    break;
                default:
                    break;
            }

        }
    });
}
//能用查询 select table where groupby having order callback
function hcdosels(s, t, w, g, h, o, callback) {
    $.get(sposelUrlByF(s, t, w, g, h, o) + "&timenow=" + new Date().getTime(),
            function (data) {
                callback(data);
            });
}
//能用查询 select table where groupby having order callback
function hcdosel(s, t, w, g, h, o, callback) {
    $.get(sposelUrlByFNoState(s, t, w, g, h, o) + "&timenow=" + new Date().getTime(),
            function (data) {
                callback(data);
            });
}
//通用导出
function toolExport() {
    hcdoExport("T.*", selTableinfo, "", "", "", "");
}
function hcdoExport(s, t, w, g, h, o) {
    var url = spPageUrl + "?action=Export&sqlinfo=" + escape("select[" + s + "]table[" + t + "]where[" + w + "]group[" + g + "]having[" + h + "]order[" + o + "]");
    url = url.replaceAll("'", "hcdhc");
    window.open(url);
}
function toolImport(parm) {
    $('#importForm')[0].reset();
    $("#importMsg").text("");
    $("#action").val("Import");
    $('#ImportShow').window({ title: "导入信息" });
    $('#ImportShow').window('open');
}
function Import(parmf, parmv) {
    if (parmf)
        $("#importForm").attr("action", (" ../ashx/sp.ashx?" + parmf + escape(parmv)));
    if ($("#importFile").val() == "") {
        $("#importMsg").text("请选择上传文件！").addClass("waringMsg");
        return;
    }
    $("#importForm").ajaxSubmit({
        success: function (message) {
            var data = JSON.parse(message);
            if (data.message == JsonResult.Success) {
                $("#importMsg").text(data.data).addClass("successMsg");
            }
            else {
                $("#importMsg").text(data.data).addClass("waringMsg");
            }
        }
    });

}
//生成理伦唯一ID
function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function NewGuid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
//调用外部winform窗体    调用的标识（方法）-主状态-信息-回调方法(必须为两个参数 funciotn (p1,p2)  没有时，为空字符串)
function callForm(callfunction, state, message, callback) {
    window.external.callform(callfunction, state, message, callback);
}
//以下可公用
function SetSelectWithObjIdName(sel, stringjson) {
    $(sel).children().remove();
    if (stringjson == "") return;
    var objData = JSON.parse(stringjson);
    $(sel).append("<option value='' selected='selected'></option>");
    for (var i = 0; i < objData.length; i++) {
        if (i == 0) {
            $(sel).append("<option value='" + objData[i].id + "' >" + objData[i].name + "</option>");
        } else {
            $(sel).append("<option value='" + objData[i].id + "'>" + objData[i].name + "</option>");
        }

    }

}
//弹给主窗体的信息
var hcdivbackinfo = "no";
/*关闭弹出框口*/
function layer_close() {
    //var parentd = parent;
    //alert(parentd.hcdivbackinfo);
    //parent.$('#parentIframe').text('我被改变了');
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

$(function () {

})

//////////////////////////////////以下为tablelist 列表处理//////////////////////////
//datable对象
var hcmtable;
//重新加载
function findreolad(isback) {
    //if (isback && isback != "no")
    //    hcmtable.ajax.reload();
    //else
    hcmtable.ajax.reload();
}
